import Vue from 'vue'
import createStore from 'app/src/store/index'
import { getPermissions } from 'src/boot/home/common-info'
import { loadToken, translateToken } from 'yz-help'
import { Dialog } from 'quasar'

const store = typeof createStore === 'function'
  ? createStore({ Vue })
  : createStore

/**
 ** sirio: 2020/02/11
 ** 自定义指令用于判断按钮权限
 ** @param id
 */
function has (el, binding, vnode) {
  let permissionId = binding.value.id
  let type = binding.value.type
  if (permissionId === null) {
    return
  }
  hasPermission(permissionId).then(res => {
    if (!res) {
      if (type === 'TAB') {
        // 若元素类型为TAB则直接移除节点
        el.parentNode.removeChild(el)
      } else {
        // 若元素类型为BUTTON则阻止点击事件
        if (vnode.componentInstance) {
          vnode.componentInstance.$off('click')
        }
        el.addEventListener('click', (e) => {
          e.stopPropagation()
          e.preventDefault()
          Dialog.create({
            title: `<p class="dialog-notice-title">
        <i class="iconfont icontubiao-52" ></i> 提示</p>`,
            message: '您无权进行此操作，请联系系统管理员',
            html: true,
            ok: {
              unelevated: true,
              label: '确认'
            }
          })
          return false
        })
      }
    }
  })
}

// 判断是否有权限
export async function hasPermission (permissionId) {
  // 判断vuex中是否存在权限映射列表
  if (store.getters.permissions.length === 0) {
    // 若不存在重新获取
    let res = await _getPermissions()
    // 提交状态管理
    store.commit('SET_PERMISSIONS', res.data)
  }

  // 提取权限映射数组
  let permissionList = store.getters.permissions

  // 判断按钮权限id在不再权限数组中
  return permissionList.includes(permissionId)
}

// 获取角色权限映射列表
function _getPermissions () {
  const token = loadToken()
  const userInfo = translateToken(token)
  const userId = userInfo.user_id
  return new Promise(resolve => {
    getPermissions(userId).then(res => {
      resolve(res)
    })
  })
}

export default has
